const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const svgCaptcha = require('svg-captcha');

// 加密工具类
class CryptoUtils {
  // 密码加密
  static async hashPassword(password) {
    const saltRounds = 10;
    return await bcrypt.hash(password, saltRounds);
  }

  // 密码验证
  static async comparePassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
  }

  // 生成JWT Token
  static generateToken(payload, expiresIn = process.env.JWT_EXPIRES_IN || '7d') {
    return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn });
  }

  // 验证JWT Token
  static verifyToken(token) {
    return jwt.verify(token, process.env.JWT_SECRET);
  }

  // 生成图形验证码
  static generateCaptcha(options = {}) {
    const defaultOptions = {
      size: 4,          // 验证码长度
      noise: 2,         // 干扰线条数
      color: true,      // 是否有颜色
      background: '#f0f0f0'  // 背景色
    };
    
    const captchaOptions = { ...defaultOptions, ...options };
    const captcha = svgCaptcha.create(captchaOptions);
    
    return {
      text: captcha.text.toLowerCase(),  // 验证码文本（转小写）
      data: captcha.data                 // SVG图片数据
    };
  }

  // 生成随机字符串
  static generateRandomString(length = 16) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }

  // 生成UUID
  static generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  // MD5哈希
  static md5(text) {
    const crypto = require('crypto');
    return crypto.createHash('md5').update(text).digest('hex');
  }

  // SHA256哈希
  static sha256(text) {
    const crypto = require('crypto');
    return crypto.createHash('sha256').update(text).digest('hex');
  }
}

module.exports = CryptoUtils; 